<template>
  <div>
    <h1>Prosemirror Demo</h1>
    <div id="content">测试 div content</div>
    <div ref="editor" id="editor"></div>
  </div>
</template>
<script>
import { schema } from "prosemirror-schema-basic";
import { EditorState } from "prosemirror-state";
import { DOMParser } from "prosemirror-model";

import { EditorView } from "prosemirror-view";
import { exampleSetup } from "prosemirror-example-setup"; // 官方示例，集成了一些基础的插件和功能，例如 Bold Heading 等
import { undo, redo, history } from "prosemirror-history";
import { keymap } from "prosemirror-keymap";
import { baseKeymap } from "prosemirror-commands";

export default {
  mounted() {
    this.initEditor();
  },
  methods: {
    initEditor() {
      const domInstance = this.$refs.editor;
      let state = EditorState.create({
        // schema,
        //  使用 DOMParser 解析 div 内容 作为 初始内容，此时 schema 字段可选
        doc: DOMParser.fromSchema(schema).parse(
          document.getElementById("content")
        ),
        plugins: [
          history(),
          keymap({
            "Mod-z": undo,
            "Mod-y": redo,
          }),
          keymap(baseKeymap),
        ],
        // plugins:exampleSetup({schema})
      });
      let view = new EditorView(domInstance, {
        state,
        dispatchTransaction(transaction) {
          console.log("dispatchTransaction", transaction);
          const newState = view.state.apply(transaction);
          view.updateState(newState);
        },
        nodeViews: {
          paragraph(node) {
            return new ParagraphView(node);
          },
        },
      });
    },
  },
};
class ParagraphView {
  constructor(node) {
    this.dom = this.contentDOM = document.createElement("p");
    if (node.content.size == 0) this.dom.classList.add("empty");
  }

  update(node) {

    if (node.type.name != "paragraph") return false;
    if (node.content.size > 0) this.dom.classList.remove("empty");
    else this.dom.classList.add("empty");
    return true;
  }
}
</script>
<style scoped>
@import "./style.css";
#editor {
  width: 100%;
  height: 600px;
  border: 1px solid #ccc;
}
</style>
